import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import services from '@/services/demo';
import { Button, Divider, Drawer, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import ModalCard from '@/components/ModalCard';
import { URL_PREFIX } from '@/constants';

const { queryListCollection, add, modify, removeById } =
  services.GradeController;

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.GradeType) => {
  const hide = message.loading('正在添加');
  try {
    await add({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: Partial<API.GradeType>) => {
  const hide = message.loading('正在修改');
  try {
    await modify(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.GradeType[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeById(selectedRows.find((row) => row.gId)?.gId || '');
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


function GradePage() {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<API.GradeType | {}>({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.GradeType>();
  const [selectedRowsState, setSelectedRows] = useState<API.GradeType[]>([]);
  const columns: ProColumns<API.GradeType>[] = [
    {
      title: '学号',
      width: 100,
      dataIndex: 'gStuid',
      hideInForm: true,
    },
    {
      title: '姓名',
      width: 70,
      dataIndex: 'gStuname',
      valueType: 'text',
    },
    {
      title: '性别',
      width: 70,
      hideInSearch: true,
      dataIndex: 'gStusex',
      render(_, record) {
        if (record.gStusex === '0')
          return <span>男</span>
        else if (record.gStusex === '1')
          return <span>女</span>
        return ''
      }
    },
    {
      title: '学院',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gStucollege',
      valueType: 'text',
    },
    {
      title: '年级',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gStugrade',
      valueType: 'text',
    },
    {
      title: '专业',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gStuprofession',
      valueType: 'text',
    },
    {
      title: '班级',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gStuclass',
      valueType: 'text',
    },
    {
      title: '博雅读书 书评报告会',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gBydsSpbgh',
      valueType: 'text',
    },
    {
      title: '博雅读书 读书沙龙',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gBydsDssl',
      valueType: 'text',
    },
    {
      title: '博雅心情 理论教学',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByxqLljx',
      valueType: 'text',
    },
    {
      title: '博雅心情 随堂练习',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByxqStlx',
      valueType: 'text',
    },
    {
      title: '博雅心情 实践锻炼',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByxqSjdl',
      valueType: 'text',
    },
    {
      title: '博雅实践 社会实践',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gBysjShsj',
      valueType: 'text',
    },
    {
      title: '博雅实践 志愿服务',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gBysjZyfu',
      valueType: 'text',
    },
    {
      title: '博雅讲坛 之江人文大讲堂',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByjtZjrwdjt',
      valueType: 'text',
    },
    {
      title: '博雅讲坛 之江大讲堂',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByjtZjdjt',
      valueType: 'text',
    },
    {
      title: '博雅讲坛 师友讲堂',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByjtSyjt',
      valueType: 'text',
    },
    {
      title: '博雅讲坛 院长下午茶',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByjtYzxwc',
      valueType: 'text',
    },
    {
      title: '博雅讲坛 主题沙龙',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByjtZtsl',
      valueType: 'text',
    },
    {
      title: '博雅讲坛 新青年月谈',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByjtXqnyt',
      valueType: 'text',
    },
    {
      title: '博雅讲坛 梦湖讲堂',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByjtMhjt',
      valueType: 'text',
    },
    {
      title: '博雅讲坛 青春有约',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByjtQcyy',
      valueType: 'text',
    },
    {
      title: '博雅修身 兴趣社团',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByxsXqst',
      valueType: 'text',
    },
    {
      title: '博雅修身 文明寝室建设',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gByxsWmqsjs',
      valueType: 'text',
    },
    {
      title: '博雅视野 出国深造',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gBysyCgsz',
      valueType: 'text',
    },

    {
      title: '博雅视野 交换学习',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gBysyJhxx',
      valueType: 'text',
    },
    {
      title: '博雅视野 游学访学',
      width: 100,
      hideInSearch: true,
      dataIndex: 'gBysyYxfx',
      valueType: 'text',
    },
    // {
    //   title: '操作',
    //   dataIndex: 'option',
    //   valueType: 'option',
    //   render: (_, record) => (
    //     <>
    //       <Button type='primary'
    //         onClick={() => {
    //           setStepFormValues((_: any) => ({...record}));
    //           handleUpdateModalVisible(true);
    //         }}
    //       >
    //         修改
    //       </Button>
    //       <Divider type="vertical" />
    //       <Popconfirm
    //         title="确定要删除吗？"
    // 				onConfirm={() => removeById(record.gId)}
    //         okText="确定"
    //         cancelText="取消"
    //       >
    //         <Button type='primary' danger >删除</Button>
    //       </Popconfirm>
    //     </>
    //   ),
    // },
  ];

  return (
    <PageContainer
      header={{
        title: '模块成绩汇总',
      }}
    >
      <ProTable<API.GradeType>
        headerTitle="请输入完整的学号或姓名进行查询"
        actionRef={actionRef}
        rowKey="gId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button key="2" type="primary">
            <a href={URL_PREFIX + '/grade/excel'} target="_blank">导出Excel</a>
          </Button>
        ]}
        request={queryListCollection}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {/* {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>批量删除</Button>
          </Popconfirm>
        </FooterToolbar>
      )} */}
      <ModalCard
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable<API.GradeType, API.GradeType>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="gId"
          type="form"
          columns={columns}
        />
      </ModalCard>
      {stepFormValues && Object.keys(stepFormValues).length > 0 ?
        <ModalCard
          onCancel={() => {
            handleUpdateModalVisible(false)
            setStepFormValues({})
          }}
          modalVisible={updateModalVisible}
        >
          <ProTable<API.GradeType, API.GradeType>
            form={{ initialValues: stepFormValues }}
            onSubmit={async (value) => {
              const success = await handleUpdate(value);
              if (success) {
                handleUpdateModalVisible(false);
                setStepFormValues({})
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="gId"
            type="form"
            columns={columns}
          />
        </ModalCard>
        : null
      }

      {/* <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.gId && (
          <ProDescriptions<API.GradeType>
            column={2}
            title={row?.gId}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.gId,
            }}
            columns={columns as ProDescriptionsItemProps<API.GradeType>[]}
          />
        )}
      </Drawer> */}
    </PageContainer>
  );
}


export default GradePage;